from app import db


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    phone = db.Column(db.String(11))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    social_auth_users = db.relationship('SocialAuthUsersocialauth', backref='localuser', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime)

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)  # python 3

    def avatar(self, size):
        return 'http://www.gravatar.com/avatar/' + md5(self.email).hexdigest() + '?d=mm&s=' + str(size)

    def __repr__(self):
        return '<User %r>' % (self.nickname)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Post %r>' % (self.body)


class SocialAuthUsersocialauth(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    provider = db.Column(db.String(10))
    openid = db.Column(db.String(55))
    extra_data = db.Column(db.String(800))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))


# flask-sqlalchemy中 backref lazy的参数实例解释和选择(https://blog.csdn.net/qq_34146899/article/details/52559747)